package com.pavlinic.mylisp;

import java.util.HashMap;
import java.util.Map;

public class ValueExpression implements Expression {

	private final Object value;

	public ValueExpression(Object value) {
		if (value == null) {
			throw new NullPointerException("Cannot create ValueExpression with null");
		}
		this.value = value;
	}

	public Expression evaluate(EvaluationContext context) {
		return this;
	}

	@Override
	public String toString() {
		return value.toString();
	}

	public Object getValue() {
		return value;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((value == null) ? 0 : value.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ValueExpression other = (ValueExpression) obj;
		if (value == null) {
			if (other.value != null)
				return false;
		} else if (!value.equals(other.value))
			return false;
		return true;
	}

	private static final Map<Class<?>, Class<?>> BOXED_TO_PRIMITIVE = new HashMap<Class<?>, Class<?>>();
	static {
		BOXED_TO_PRIMITIVE.put(Integer.class, int.class);
	}

	public Class<?> getType() {
		final Class<?> clazz = value.getClass();
		final Class<?> primitiveClass = BOXED_TO_PRIMITIVE.get(clazz);
		if (primitiveClass != null) {
			return primitiveClass;
		}
		return clazz;
	}
}
